#!/bin/bash
#===================================================================================
# FILE: wallpaper-rotate
# DESCRIPTION: select image from directory rotationally and generates link to it
# AUTHOR: Leonardo Marco
# VERSION: 1.0
# CREATED: 2020.04.20
# LICENSE: GNU General Public License v3.0
#===================================================================================


#### CONFIG ############################################################
wps_src="/usr/share/backgrounds/wallpapers-alinz/"				# Directory where all images are stored
wp_rotate_dest="/usr/share/backgrounds/wallpapers-alinz/"		# Directory where rotate wallpaper link will be saved
wp_rotate_name="wp-rotate"										# Name of rotate wallpaper link (extension will be completed automatically)
########################################################################

shopt -s extglob


# Checks
if [ ! -d "$wps_src" ] || [ ! -r "$wps_src" ]; then
	echo "Cant access to wallpapers directory $wps_src" 1>&2
	exit 1
fi
if [ ! -w  "$wp_rotate_dest" ]; then
	echo "Cant write in destination directory $wp_rotate_dest" 1>&2
	exit 1
fi

# Put all wallpaper paths in array
IFS=$'\n'
wps_paths=($(find "$wps_src" -type f))					# Array with all wallpapers path

# Get today wallpaper position in array
n=${#wps_paths[*]}										# Num of items in array
d=$(date +%j); d=${d##+(0)}								# Today day of year
n=$((d%n))												# Today array position

# Get today wallpaper path
wp_selected="${wps_paths[$n]}"
echo -e "Selected wallpaper is:\t\t$wp_selected"

# Generate link
wp_link="${wp_rotate_dest}/${wp_rotate_name}.${wp_selected##*.}"
echo -e "Creating wallpaper link in:\t$wp_link"
ln -sf "$wp_selected" "$wp_link"
